package com.example.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Log;
import com.example.entity.User;
import com.example.service.LogService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/*
*切面处理器  用于专门处理切面 类似于监控
*/
@Component
@Aspect
public class LogAspect {
    @Resource
    LogService logService;

    @Around("@annotation(autoLog)")
    public Object doAround(ProceedingJoinPoint joinPoint, AutoLog autoLog) throws Throwable {



        //操作内容 在注解中已经定义了value() 在需要切入的接口上去写上对应的操作内容即可
        String log = autoLog.value();

        //操作时间
        String logtime = DateUtil.now();

        //操作人
        String username = null;
        Result result = (Result) joinPoint.proceed();

        User userLogin = null;

        Object data = result.getData();
        if (data instanceof User){
            userLogin = (User) data;
            username = userLogin.getUsername();

        }

        if (ObjectUtil.isNotEmpty(userLogin)){
            username = userLogin.getUsername();
        }

        //操作人ip
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();
//        System.out.println(request.getSession().setAttribute("user",user);
//        System.out.println(request.getSession().getAttribute("user"));


        //先不着急返回给前端 可能还有事要做 比如记录日志信息
        Log loglist = new Log(null,log,logtime,username,ip);
        logService.add(loglist);

        //返回给前端
        return result;
    }
}
